package com.gxks.lhs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxks.lhs.entity.Goods;
import com.gxks.lhs.entity.Order;
import com.gxks.lhs.mapper.GoodsMapper;
import com.gxks.lhs.mapper.OrderMapper;
import com.gxks.lhs.service.IGoodsService;
import com.gxks.lhs.service.IOrderService;
import com.gxks.lhs.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.beans.Transient;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author LuoHaisong
 * @since 2023-05-19
 */

@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private IGoodsService goodsService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean cancellationOfOrderById(String id) {
        log.info("管理员取消订单，订单id为：" + id);
        //构建表达式，更新订单状态
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(Order::getId, id);
        updateWrapper.set("status", 5);
        //获取当前订单
        Order order = getById(id);
        //往买家账户充值，退款
        userService.recharge(order.getBuyerId(), order.getTotalPrice());
//        商品重新上架
        goodsService.updateGoodsStatus(order.getProductId(), 1);
        //更新订单状态
        return update(updateWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean cancellationOfOrderByIdAndUserId(String userId, String id) {
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(Order::getId, id);
        updateWrapper.lambda().eq(Order::getBuyerId, userId);
        updateWrapper.set("status", 5);
        //获取当前订单
        Order order = getById(id);
        //往买家账户充值，退款
        userService.recharge(order.getBuyerId(), order.getTotalPrice());
        return update(updateWrapper);
    }

    @Override
    public boolean refundOrderById(Integer id) {
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(Order::getId, id);
        updateWrapper.set("status", 5);
        //获取当前订单
        Order order = getById(id);
        //往买家账户充值，退款
        userService.recharge(order.getBuyerId(), order.getTotalPrice());
        return update(updateWrapper);
    }

    @Override
    public Page<Order> findOrders(String id, Integer status, Instant beginTime, Instant endTime, Integer current, Integer size) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        log.info("查询订单，id为：" + id + "，状态为：" + status + "，开始时间为：" + beginTime + "，结束时间为：" + endTime);
        queryWrapper.lambda().eq(!StringUtils.isEmpty(id), Order::getId, id)
                .eq(status != null, Order::getStatus, status)
                .between(beginTime != null, Order::getCreateTime, beginTime, endTime)
                .orderByDesc(Order::getCreateTime);
        return page(new Page<>(current, size), queryWrapper);
    }

    @Override
    public Page<Order> findAllOrders(Integer current, Integer size) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(Order::getCreateTime);
        return page(new Page<>(current, size), queryWrapper);
    }

    @Override
    public Order findOrderByIdOfUser(String id, String userId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Order::getId, id).and(i -> i.eq(Order::getBuyerId, userId).or().eq(Order::getSellerId, userId));
        return getOne(queryWrapper);
    }

    @Override
    public Order findOrderByIdOfAdmin(String id) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Order::getId, id);
        return getOne(queryWrapper);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createOrder(Order order) {
//      生成订单id，时间+当前时间戳+随机数
        order.setId("T" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")) + Math.round(Math.random() * 100000));
        log.info("用户下单了，用户id：" + order.getBuyerId() + "，商品id：" + order.getProductId());
        System.out.println("订单id：" + order.getId());
        //查询商品信息
        Goods goods = goodsService.findGoodsById(order.getProductId());
        if (goods == null) {
            return null;
        }
        if (goods.getStatus() != 1) {
            return null;
        }
        //把商品信息放入订单，订单状态改为待支付
        order.setProductName(goods.getTitle());
        order.setTotalPrice(goods.getPrice());
        order.setPic(goods.getPicture());
        order.setSellerId(goods.getUserId());
        order.setSellerName(goods.getUserName());
        order.setStatus(1);
        save(order);
        //改变商品状态
        goodsMapper.update(new Goods().setStatus(2), new QueryWrapper<Goods>().lambda().eq(Goods::getId, order.getProductId()));
        return order.getId().toString();
    }

    @Override
    public Page<Order> findOrdersByBuyerId(Integer buyerId, Integer current, Integer size) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(Order::getBuyerId, buyerId);
        queryWrapper.lambda().orderByDesc(Order::getCreateTime);
        return page(new Page<>(current, size), queryWrapper);
    }

    @Override
    public Page<Order> findUserOrderList(Order order, Integer current) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(order.getSellerId() != null, Order::getSellerId, order.getSellerId());
        queryWrapper.lambda().eq(order.getBuyerId() != null, Order::getBuyerId, order.getBuyerId());
        queryWrapper.lambda().eq(order.getStatus() != 0, Order::getStatus, order.getStatus());
        queryWrapper.lambda().orderByDesc(Order::getCreateTime);
        return page(new Page<>(current, 10), queryWrapper);
    }

    @Override
    public boolean updateOrder(Order order) {
        LambdaUpdateWrapper<Order> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Order::getId, order.getId())
                .eq(order.getBuyerId() != null, Order::getBuyerId, order.getBuyerId())
                .eq(order.getSellerId() != null, Order::getSellerId, order.getSellerId())
                .set(Order::getStatus, order.getStatus())
                .set(order.getLogisticsNum() != null, Order::getLogisticsNum, order.getLogisticsNum());
        return update(lambdaUpdateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean balancePayOrder(String userId, String orderId) {
        Order order = getById(orderId);
        if (order == null) {
            return false;
        }
        if (order.getStatus() != 1) {
            return false;
        }
        if (!userService.balancePay(userId, order.getTotalPrice())) {
            return false;
        }
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Order::getId, orderId)
                .eq(Order::getBuyerId, userId).set(Order::getStatus, 2)
                .set(Order::getPayType, "banlance")
                .set(Order::getPayName, "余额支付")
                .set(Order::getPayTime, LocalDateTime.now());
        return update(updateWrapper);
    }

    @Override
    public boolean testPayOrder(String userId, String orderId) {
        Order order = getById(orderId);
        if (order == null) {
            return false;
        }
        if (order.getStatus() != 1) {
            return false;
        }
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Order::getId, orderId)
                .eq(Order::getBuyerId, userId).set(Order::getStatus, 2)
                .set(Order::getPayType, "testPay")
                .set(Order::getPayName, "测试支付")
                .set(Order::getPayTime, LocalDateTime.now());
        return update(updateWrapper);
    }

    @Override
    public boolean receipt(String userId, String orderId) {
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Order::getId, orderId)
                .eq(Order::getBuyerId, userId)
                .set(Order::getStatus, 3);
        return update(updateWrapper);
    }
}
